package com.xzcs.service.sysmgr;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzcs.mapper.operating.OperatingMapper;
import com.xzcs.mapper.sequence.SequenceMapper;
import com.xzcs.service.BaseService;
import com.xzcs.util.common.DateUtils;
import com.xzcs.util.common.StringUtils;
import com.xzcs.util.web.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class OperatingService extends BaseService {

	@Autowired
	private OperatingMapper operatingMapper;
	@Autowired
	private SequenceMapper sequenceMapper;

	private static ExecutorService executor = Executors.newCachedThreadPool();

	public PageInfo<Map<String, Object>> findOperatings(HttpServletRequest request){
		String pageNum = RequestUtils.getValue(request, "page");//页数
		String pageSize = RequestUtils.getValue(request, "rows");//每页条数
		pageNum = pageNum.equals("") ? "1" : pageNum;
		pageSize = pageSize.equals("") ? getDefaultPageSize() : pageSize;
		Map<String, Object> params = RequestUtils.getRequestMap(request);
		String startTime = RequestUtils.getValue(request, "startTime");
		String endTime = RequestUtils.getValue(request, "endTime");
		startTime = startTime.equals("") ? DateUtils.getDay(-7, "yyyy-MM-dd") : startTime;
		endTime = endTime.equals("") ? DateUtils.getToday("yyyy-MM-dd") : endTime;
		params.put("startTime", startTime);
		params.put("endTime", endTime);
		PageHelper.startPage(StringUtils.toInt(pageNum), StringUtils.toInt(pageSize));
		List<Map<String, Object>> list = operatingMapper.findOperatings(params);
		PageInfo<Map<String, Object>> page = new PageInfo<Map<String, Object>>(list);
		return page;
	}

	public void insertLog(HttpServletRequest request, Map<String, Object> params){
		executor.execute(new LogTask(request, params));
	}

	public class LogTask implements Runnable {
		private HttpServletRequest request;
		private Map<String, Object> params;
		public LogTask(HttpServletRequest request, Map<String, Object> params) {
			this.request = request;
			this.params = params;
		}
		@Override
		public void run() {
			String seqId = DateUtils.getToday("yyyyMMddHHmmss") + sequenceMapper.getSequenceValue("seq_log_id");
			params.put("seqId", seqId);
			operatingMapper.insertOperating(params);
		}
	}
}
